<template>
  <div class="material-in-bound-page">
    <!-- 搜索区域 -->
    <div class="screenConditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <SelectBlock
            :allowClear="true"
            v-model="conditions.orgCode"
            @change="blockChange($event)"
          ></SelectBlock>
          <a-input placeholder="请输入物料名称" v-model="conditions.name" />
        </template>
        <template slot="operate">
          <a-button type="primary" @click="queryData(selectTreeNode.dicValue)">
            查询
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <!-- 结果区域 -->
    <div class="result-container">
      <div class="result-body">
        <div class="tree-warp" v-loading="treeLoading">
          <div class="tree-body" :class="treeVisible && 'open'">
            <div class="header">物料类型</div>
            <div class="tree-content">
              <div class="body">
                <a-tree
                  :default-expanded-keys="expandedKeys"
                  :expanded-keys="expandedKeys"
                  :selected-keys="selectedKeys"
                  blockNode
                  show-icon
                  default-expand-all
                  :tree-data="treeData"
                  @expand="onExpand"
                  @select="treeSelect"
                  :replaceFields="{
                    children: 'childList',
                    title: 'dicDesc',
                    key: 'dicValue',
                  }"
                >
                  <template slot="title" slot-scope="{ childList, dicDesc }">
                    <div class="tree-node-item">
                      <div
                        class="icon"
                        :class="childList && childList.length > 0 && 'folder'"
                      ></div>
                      <div class="name">
                        {{ dicDesc }}
                      </div>
                    </div>
                  </template>
                </a-tree>
              </div>
            </div>
          </div>
          <div
            class="close-button"
            :class="treeVisible && 'open'"
            @click="treeVisible = !treeVisible"
          ></div>
        </div>
        <div class="table-warp" v-loading="loading">
          <div class="operate-body" v-if="conditions.orgCode && addBtnShow">
            <a-button
              type="primary"
              @click="
                (operateModalType = 0),
                  (operateModalTitle = '新增'),
                  (visible = true)
              "
            >
              新增
            </a-button>
          </div>
          <div class="table-body">
            <vxe-table
              height="100%"
              class="scrollbarStyle"
              align="center"
              :data="tableData"
              :column-config="{ resizable: true }"
            >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column
                field="name"
                title="物料名称"
                width="200"
              ></vxe-column>
              <vxe-column field="norms" title="规格" width="100"></vxe-column>
              <vxe-column field="model" title="型号" width="100"></vxe-column>
              <vxe-column
                field="material"
                title="材质"
                width="100"
              ></vxe-column>

              <vxe-column
                field="unit"
                title="计量单位"
                width="150"
              ></vxe-column>
              <!-- <vxe-column
                field="price"
                title="单价（元）"
                width="120"
              ></vxe-column> -->
              <vxe-column
                field="supplier"
                title="供应商"
                width="150"
              ></vxe-column>
              <vxe-column
                field="materialTypeName"
                title="物料类型"
                width="180"
              ></vxe-column>
              <vxe-column
                field="code"
                title="属性编码"
                width="100"
              ></vxe-column>
              <vxe-column
                field="goodsNo"
                title="物资编码"
                width="200"
              ></vxe-column>
              <!-- <vxe-column
                field="taxRate"
                title="税率（%）"
                width="200"
              ></vxe-column> -->
              <vxe-column
                field="operate"
                width="200"
                title="操作"
                fixed="right"
              >
                <template #default="{ row }">
                  <div class="text-button-group">
                    <a-button
                      type="link"
                      @click="
                        (id = row.id),
                          (operateModalType = 2),
                          (operateModalTitle = '详情'),
                          (visible = true)
                      "
                      >查看</a-button
                    >
                    <a-button
                      type="link"
                      @click="
                        (id = row.id),
                          (operateModalType = 1),
                          (operateModalTitle = '编辑'),
                          (visible = true)
                      "
                      :disabled="row.isUse > 0 || !conditions.orgCode"
                      >编辑</a-button
                    >
                    <a-button
                      type="link"
                      class="danger"
                      @click="deleteConfirm(row)"
                      :disabled="row.isUse > 0 || !conditions.orgCode"
                      >删除</a-button
                    >
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div class="pager-body">
            <vxe-pager
              background
              :current-page.sync="pager.page"
              :page-size.sync="pager.pageSize"
              :total="pager.total"
              :layouts="[
                'PrevPage',
                'JumpNumber',
                'NextPage',
                'Sizes',
                'FullJump',
              ]"
              @page-change="paginationChange"
            >
              <template #left>
                <div class="vxe-pager-left-tip-container">
                  第<span>1</span>到<span
                    >{{ Math.ceil(pager.total / pager.pageSize) }}页 </span
                  >共<span>{{ pager.total }}</span
                  >条记录
                </div>
              </template>
            </vxe-pager>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增编辑弹窗 -->
    <OperateModal
      :type.sync="operateModalType"
      :title="operateModalTitle"
      :visible.sync="visible"
      :block="conditions.orgCode"
      :category.sync="selectTreeNode.dicValue"
    ></OperateModal>
  </div>
</template>

<script>
import ScreenConditions from "@/components/ScreenConditions";
import bjRangeCalendar from "@/components/bj-range-calendar";
import TableView from "@/components/tableView";
import paginationMixins from "@/mixins/pagination";
import OperateModal from "./components/OperateModal";
import SelectBlock from "@/components/wisdom-beam/SelectBlock";
import {
  queryMaterialBaseList,
  materialOutStoragedelete,
  materialTreeList,
} from "@/api/wisdom-beam/material-app";
import routerKeep from "@/mixins/routerKeep.js";
import { addAttributeByKey, flatTreeData } from "@/utils";
export default {
  components: {
    ScreenConditions,
    bjRangeCalendar,
    TableView,
    OperateModal,
    SelectBlock,
  },
  mixins: [paginationMixins, routerKeep],
  data() {
    return {
      selectTreeNode: {},
      treeLoading: true,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      addBtnShow: false,
      treeVisible: true,
      id: "",
      operateModalTitle: "",
      operateModalType: 0,
      loading: true,
      visible: false,
      conditions: {
        //标段
        orgCode: undefined,
        //物料名称
        name: "",
      },
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  mounted() {},
  methods: {
    getTreeList() {
      return new Promise((resolve, reject) => {
        this.treeLoading = true;
        materialTreeList({ dictType: "material_category" })
          .then((res) => {
            let { data } = res;
            let source = data?.result ?? [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            let flatData = flatTreeData(source, "childList");
            this.treeData = filterData;
            this.expandedKeys = flatData.map((v) => v.dicValue);
            let firstSonNode = flatData.find(
              (v) => !v.childList || v.childList.length == 0
            );
            this.selectTreeNode = firstSonNode;
            this.selectedKeys = [firstSonNode?.dicValue];
            if (firstSonNode) {
              this.addBtnShow = true;
            } else {
              this.addBtnShow = false;
            }
            this.queryData(firstSonNode?.dicValue);
            resolve();
          })
          .catch((_) => {
            this.expandedKeys = [];
            this.treeData = [];
            this.selectedKeys = [];
            this.addBtnShow = false;
            this.selectTreeNode = {};
            this.queryData();
            reject();
          })
          .finally((_) => {
            this.treeLoading = false;
          });
      });
    },
    //查询列表数据
    queryData(type = "") {
      let { page, pageSize } = this.pager;
      let { orgCode, name } = this.conditions;
      this.loading = true;
      queryMaterialBaseList({
        orgCode: orgCode?.key || "",
        name: name,
        supplier: "",
        type,
        page,
        pageSize,
      })
        .then((res) => {
          let { data } = res;
          this.tableData = data.result.records;
          this.pager.total = data.result.total;
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    treeSelect(selectedKeys, e) {
      let { selected } = e;
      let { dicValue, childList } = e.node.dataRef;
      this.selectTreeNode = e.node.dataRef;
      if (selected) {
        this.selectedKeys = selectedKeys;
        if (childList && childList.length > 0) {
          this.addBtnShow = false;
        } else {
          this.addBtnShow = true;
        }
        this.queryData(dicValue);
      }
    },

    //监听标段切换
    blockChange(value) {
      this.getTreeList();
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.queryData(this.selectTreeNode?.dicValue);
    },

    //删除
    deleteConfirm(record) {
      let { id } = record;
      let _this = this;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            materialOutStoragedelete({
              id,
            })
              .then(() => {
                _this.$message.success("操作成功！");
                _this.queryData();
                resolve();
              })
              .catch((_) => {
                _this.$message.error("操作失败，请稍后重试！");
                reject();
              });
          }).catch(() => console.log("Oops errors!"));
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },

    //跳转新增页面
    gotoAdd() {},
  },
};
</script>

<style lang="less" scoped>
.material-in-bound-page {
  height: 100%;
  padding: 0 0 10px 10px;
  box-sizing: border-box;
  .flex();
  flex-direction: column;
  .result-container {
    flex: 1;
    background: #fff;
    overflow: hidden;
    .flex();
    flex-direction: column;
    .result-header {
      height: 60px;
      flex-shrink: 0;
      .flex();
      align-items: center;
      padding: 0 26px 0 20px;
      .title {
        font-size: 18px;
        color: #525a5d;
        position: relative;
        padding-left: 14px;
        &::before {
          content: "";
          position: absolute;
          width: 3px;
          top: 50%;
          transform: translateY(-50%);
          left: 0;
          height: 16px;
          //   background: var(--primary-color);
        }
      }
      .operate-container {
        margin-left: auto;
      }
    }
    .result-body {
      flex: 1;
      width: 100%;
      overflow: hidden;
      background: #f3f4f6;
      .flex();
      .tree-warp {
        margin-right: 2px;
        background: #fff;
        flex-shrink: 0;
        margin-right: 15px;
        position: relative;
        .close-button {
          position: absolute;
          width: 8px;
          height: 56px;
          background: url("https://jszhgd.cn/static/pc/trial/close.png");
          background-size: 100% 100%;
          right: -8px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          &.open {
            background: url("https://jszhgd.cn/static/pc/trial/open.png");
            background-size: 100% 100%;
          }
        }
        .tree-body {
          width: 0;
          height: 100%;
          transition: 0.3s;
          overflow: hidden;
          .flex();
          flex-direction: column;
          &.open {
            width: 300px;
          }
          .header {
            height: 18px;
            border-left: 3px solid var(--primary-color);
            font-size: 18px;
            color: #525a5d;
            align-items: center;
            .flex();
            padding-left: 10px;
            margin: 12px;
            flex-wrap: nowrap;
            white-space: nowrap;
            flex-shrink: 0;
          }
          .tree-content {
            flex: 1;
            overflow: hidden;
            .body {
              height: 100%;
              .custom-scrollbar();
              padding: 0 10px;
              /deep/.ant-tree {
                li {
                  .ant-tree-node-content-wrapper {
                    width: calc(100% - 24px);
                    .tree-node-item {
                      overflow: hidden;
                      .flex();
                      align-items: center;
                      .icon {
                        width: 16px;
                        height: 16px;
                        background: url("https://jszhgd.cn/static/pc/file.png");
                        margin-right: 6px;
                        &.folder {
                          background: url("https://jszhgd.cn/static/pc/folder.png");
                          background-size: 100% 100%;
                        }
                      }
                      .name {
                        flex: 1;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      .table-warp {
        flex: 1;
        width: 1px;
        .flex();
        flex-direction: column;
        .operate-body {
          height: 60px;
          background: #fff;
          .flex();
          align-items: center;
          justify-content: flex-end;
          padding-right: 10px;
        }
        .table-body {
          flex: 1;
          overflow: hidden;
        }
        .pager-body {
          height: 80px;
        }
      }
    }
  }
}
</style>
